//
//  ImageProcessViewController.m
//  图片故事
//
//  Created by 大帅逼 on 16/1/6.
//  Copyright © 2016年 helloApp. All rights reserved.
//

#import "ImageProcessViewController.h"
#import "CreateManagerViewController.h"
#import "UIImageView+WebCache.h"
#import "Header.h"
#import "FilterCollectionViewCell.h"
#import "FilterData.h"
#import "MBProgressHUD+PKX.h"
#import "LocaData.h"
#import "POptionCollectionViewCell.h"
#import "GPUImage.h"
#import "FilterAttributeView.h"
#import "FilterObject.h"
#import "ChancePhotoQualityViewController.h"
#import "FWApplyFilter.h"
#import "EffectView.h"
#import "WriteMarkViewController.h"
#import "ShareAndSaveViewController.h"

@interface ImageProcessViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>{

    BOOL        _isShowAttribute;
    BOOL        _isEffectShow;
    NSInteger   _oldIndex;
    NSInteger   _newIndex;
    NSInteger   _oldFilterIndex;
    NSInteger   _newFilterIndex;
}

@property(nonatomic,strong) UIImageView         *contextImageView;
@property(nonatomic,strong) UIAlertController   *alertController;
@property(nonatomic,strong) UICollectionView    *filterCollection;
@property(nonatomic,strong) UIButton            *scaleBtn;
@property(nonatomic,assign) CGFloat             scaleFloat;
@property(nonatomic,copy)   NSString            *filterName;
@property(nonatomic,strong) CIImage             *oldCIImage;
@property(nonatomic,strong) CIContext           *context;
@property(nonatomic,strong) CIFilter            *filter;
@property(nonatomic,strong) UICollectionView    *optionCollection;
@property(nonatomic,strong) FilterAttributeView *attributeView;
@property(nonatomic,strong) UIImage             *sameImage;
@property(nonatomic,strong) EffectView          *effectView;
@property(nonatomic,strong) UIButton            *resetBtn;
@property(nonatomic,strong) NSMutableArray      *filterArray;

@end

@implementation ImageProcessViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化界面
    [self initView];
    
    // 初始化导航控制器
    [self initNavigation];
}

/* - - - - - - - - - - - - - - -初始化界面 - - - - - - - - - - - -  */

- (void) initView {

    [self.view setBackgroundColor:[UIColor blackColor]];
    
    _newIndex = 0;
    
    _oldIndex = 0;
    
    _oldFilterIndex = -1;
    
    _scaleFloat = 0.8;
    
    _isShowAttribute = NO;
    
    _isEffectShow = NO;
    
    _filterArray = [[NSMutableArray alloc] init];
    
    _contextImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, My_Height(84), SCREEN_W,SCREEN_H - My_Height(284))];
    
    [_contextImageView setContentMode:UIViewContentModeScaleAspectFit];
    
    [_contextImageView setBackgroundColor:[UIColor blackColor]];
    
    [self.view addSubview:_contextImageView];
    
    [self setCurrImagePhotoQualit];
    
    // 添加滤镜视图
    [self.view addSubview:self.filterCollection];
    
    // 添加处理选项视图
    [self.view addSubview:self.optionCollection];
    
    // 添加按钮
    [self.view addSubview:self.scaleBtn];
    
    [self.view addSubview:self.resetBtn];
    
    // 添加调节的视图
    _attributeView = [[FilterAttributeView alloc] initWithFrame:CGRectMake(SCREEN_W, My_Height(89) + (SCREEN_H - My_Height(284)), SCREEN_W, My_Height(135)) oldImage:self.contextImageView.image imageView:self.contextImageView];
    
    [_attributeView setBackgroundColor:[UIColor blackColor]];
    
    [self.view addSubview:_attributeView];
    
    // 添加效果视图
    [self.view addSubview:self.effectView];
    
    // 设置键值观察
    [self addObserver:self forKeyPath:@"oldImage" options:NSKeyValueObservingOptionNew context:nil];
    
    [self addObserver:self forKeyPath:@"scaleFloat" options:NSKeyValueObservingOptionNew context:nil];
    
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setCurrImagePhotoQualit) name:@"changePhotoQualit" object:nil];
}

#pragma mark -- 设置导航控制器样式

- (void) initNavigation {
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:20]}];
    
    self.title = @"美化图片";
    
    // 设置导航控制器左右按钮
    UIBarButtonItem *backItme = [[UIBarButtonItem alloc] initWithTitle:@"返回 " style:UIBarButtonItemStylePlain target:self action:@selector(action_backItmeClickEvent)];
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.leftBarButtonItem = backItme;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(action_createItemClickEvent)];
    
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma mark -- 表格视图数据源方法的相关设置

// 设置章节数

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}

// 设置每个章节的item个数

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    if (collectionView.tag == 102) {
        
        FilterData *filterData = [[FilterData alloc] init];
        NSArray *groupTitle = [filterData readFilterGroupTitle];
        
        return [groupTitle count];
    }else {
    
        return [[LocaData readPrecessOption] count];
    }
}

// 设置item的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (collectionView.tag == 102) {
        
        return CGSizeMake(My_Height(80), My_Height(100));
    }else {
    
        return CGSizeMake(SCREEN_W / 4, My_Height(60));
    }
}

// 设置每个item的数据

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView.tag == 102) {
        
        FilterCollectionViewCell *filterCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"filterCell" forIndexPath:indexPath];
        
        FilterData *filterGroup = [[FilterData alloc] init];
        
        NSArray *titleGroup = [filterGroup readFilterGroupTitle];
        
        [filterCell.nameLabel setText:[titleGroup objectAtIndex:indexPath.row]];
        
        [filterCell.filterImageView setImage:[UIImage imageNamed:[titleGroup objectAtIndex:indexPath.row]]];
        
        [_filterArray addObject:filterCell];
        
        return filterCell;
    }else {
    
        POptionCollectionViewCell *optionCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"optionCell" forIndexPath:indexPath];
        
        [optionCell setPrecessOption:[[LocaData readPrecessOption] objectAtIndex:indexPath.row]];
        
        if (_newIndex == indexPath.row) {
            
            [optionCell.optionTitleLabel setTextColor:[UIColor yellowColor]];
        }
        
        return optionCell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (collectionView.tag == 102) {
        
        FilterData *filterData = [[FilterData alloc] init];
        
        NSArray *chanceFilterGroup = [filterData readFilterGroup];
        
        _filterName = [chanceFilterGroup objectAtIndex:indexPath.row];
        
        _scaleFloat = 0.8;
        
        _newFilterIndex = indexPath.row;
        
        [self reflshFilterClickBtn];
        
        [self filterImageWithScale:_scaleFloat filterName:_filterName];
        
        [self.effectView reflshEffectClickItem:-1];
    }else {
    
        switch (indexPath.row) {
            case 0:
                
                if (_isEffectShow) {
                    
                    [self showEffectView];
                }
                
                if (_isShowAttribute) {
                    
                    [self showAttributeView];
                }
                
                _newIndex = 0;
                
                [self refleshClickBtn:_newIndex];
                
                break;
            case 1:
                
                _newIndex = 1;
                
                [self refleshClickBtn:_newIndex];
                
                [self showEffectView];
                
                break;
            case 2:
                
                _newIndex = 2;
                
                [self refleshClickBtn:_newIndex];
                
                // 显示属性调节视图
                [self showAttributeView];
                
                break;
            case 3:
                
                // 跳转到水印视图
                [self showMarkViewController];
                
                break;
                
            default:
                break;
        }
    }
}

#pragma mark -- 点击事件相关

- (void) action_backItmeClickEvent {
    
    [self presentViewController:self.alertController animated:YES completion:nil];
}

- (void) action_createItemClickEvent {
    
    ShareAndSaveViewController *shareVC = [[ShareAndSaveViewController alloc] init];
    
    shareVC.resultImage = self.contextImageView.image;
    
    [self.navigationController pushViewController:shareVC animated:YES];
}

// 滑动滑动条触发
- (void) action_changeSliderScale : (UISlider *) slider {

    self.scaleFloat = slider.value;
}

// 设置滤镜化参数
- (void) action_scaleBtnClickEvent {
    
    ChancePhotoQualityViewController *chacePhotoQualityVC = [[ChancePhotoQualityViewController alloc] init];
    
    [self.navigationController pushViewController:chacePhotoQualityVC animated:YES];
}

// 设置对应的滤镜化
- (void) filterImageWithScale : (CGFloat) scale filterName : (NSString *) filterName {
    
    if (filterName.length <= 0) {
        
        [MBProgressHUD showError:@"你还没用选择滤镜"];
    }else {
    
        _oldCIImage = [[CIImage alloc] initWithImage:_oldImage];
        
        _filter = [CIFilter filterWithName:filterName keysAndValues:kCIInputImageKey,_oldCIImage,nil];
        
        [_filter setDefaults];
        
        CIImage *outImage = [_filter outputImage];
        
        CGImageRef cgImage =[self.context createCGImage:outImage fromRect:[outImage extent]];
        
        UIImage* resultImage = [UIImage imageWithCGImage:cgImage];
        
        CGImageRelease(cgImage);
        
        [self.contextImageView setImage:resultImage];
        
        _filterImage = resultImage;
    }
}

// 设置调节视图的隐藏与现实
- (void) showAttributeView {

    if (_isShowAttribute == NO) {
        
        if (_isEffectShow) {
            
            [self showEffectView];
        }
        
        [UIView animateWithDuration:0.5 animations:^{
            
            [self.attributeView setFrame:CGRectMake(0, My_Height(89) + (SCREEN_H - My_Height(284)), SCREEN_W, My_Height(135))];
            
        } completion:^(BOOL finished) {
            
            _isShowAttribute = YES;
        }];
    }else {
    
        [UIView animateWithDuration:0.5 animations:^{
           
            [self.attributeView setFrame:CGRectMake(SCREEN_W, My_Height(89) + (SCREEN_H - My_Height(284)), SCREEN_W, My_Height(135))];
            
        } completion:^(BOOL finished) {
            
            _isShowAttribute = NO;
        }];
    }
}

- (void) showEffectView {

    if (self.effectView.alpha >0) {
        
        [UIView animateWithDuration:0.5 animations:^{
           
            self.effectView.alpha = 0;
            
            _isEffectShow = NO;
        }];
    }else {
    
        [UIView animateWithDuration:0.5 animations:^{
            
            if (_isShowAttribute == NO) {
                
                self.effectView.alpha = 1;
            }else {
            
                [self showAttributeView];
                self.effectView.alpha = 1;
            }
            
            _isEffectShow = YES;
        }];
    }
}

- (void) showMarkViewController {

    WriteMarkViewController *markVC = [[WriteMarkViewController alloc] init];
    
    markVC.loadImage = self.contextImageView.image;
    
    markVC.callBack = ^void(UIImage *backImage){
    
        _oldImage = backImage;
        
        [self.contextImageView setImage:backImage];
    };
    
    [self.navigationController pushViewController:markVC animated:YES];
}

- (void) refleshClickBtn : (NSInteger ) index {

    NSArray *cells = [self.optionCollection visibleCells];
    
    POptionCollectionViewCell *cell = (POptionCollectionViewCell *)[cells objectAtIndex:index];
    
    [cell.optionTitleLabel setTextColor:[UIColor yellowColor]];
    
    POptionCollectionViewCell *oldCell = (POptionCollectionViewCell *)[cells objectAtIndex:_oldIndex];
    
    [oldCell.optionTitleLabel setTextColor:[UIColor whiteColor]];
    
    _oldIndex = index;
}

- (void) reflshFilterClickBtn {
    
    if (_newFilterIndex != -1) {
        
        FilterCollectionViewCell *cell = (FilterCollectionViewCell *)[_filterArray objectAtIndex:_newFilterIndex];
        
        [cell.nameLabel setTextColor:[UIColor yellowColor]];
    }
    
    if (_oldFilterIndex != -1) {
        
        FilterCollectionViewCell *oldCell = (FilterCollectionViewCell *)[_filterArray objectAtIndex:_oldFilterIndex];
        
        [oldCell.nameLabel setTextColor:[UIColor whiteColor]];
    }
    
    _oldFilterIndex = _newFilterIndex;
}

- (void) action_resetBtnClickEvent {

    [self.contextImageView setImage:_sameImage];
    
    _newFilterIndex = -1;
    
    [self reflshFilterClickBtn];
    
    [self.effectView reflshEffectClickItem:-1];
}

- (void)unsetFilterItem {

    _newFilterIndex = -1;
    
    [self reflshFilterClickBtn];
}

#pragma mark -- 通过此方法公开当前正在处理的图片
- (UIImage *) getCurrImageViewImage {

    return self.contextImageView.image;
}

- (UIImage *)getOldImage {

    return _oldImage;
}

#pragma mark -- 处理当前显示图片的现实质量
- (void) setCurrImagePhotoQualit {
    
    UIImage *loadImage;
    
    // 根据本地用户习惯对图片进行缩放处理
    loadImage = [[FilterObject shardFilterObject] scaleImageWithImage:_sameImage];

    [_contextImageView setImage:loadImage];
    
    _oldImage = loadImage;
    
    _filterImage = loadImage;
    
    NSLog(@"selectScale = %lf , loadScale = %lf", _oldImage.size.width,loadImage.size.width);
}

#pragma mark -- 添加键值观察
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"oldImage"]) {
        
        if ([_isNewImage isEqualToString:@"yes"]) {
            
            [self action_resetBtnClickEvent];
        }
        
        _sameImage = _oldImage;
        
        [self setCurrImagePhotoQualit];
        
    }else if ([keyPath isEqualToString:@"scaleFloat"]) {
    
        [self filterImageWithScale:_scaleFloat filterName:_filterName];
    }
}

#pragma mark -- 懒加载
- (UIAlertController *)alertController {

    if (!_alertController) {
        
        _alertController = [UIAlertController alertControllerWithTitle:@"放弃编辑？" message:@"放弃编辑将不会保存图片" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:@"放弃" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"chanceImage" object:_oldImage];
//            
//            self.contextImageView.image = nil;
            
            [self action_resetBtnClickEvent];
            
            [[CreateManagerViewController shardManger] showImageProcessViewControllerWithImage:nil];
        }];
        
        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"继续编辑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [_alertController addAction:sureBtn];
        
        [_alertController addAction:cancelBtn];
    }
    
    return _alertController;
}

- (UICollectionView *) filterCollection {

    if (!_filterCollection) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
        [layout setMinimumInteritemSpacing:0.0];
        
        [layout setMinimumLineSpacing:5.0];
        
        _filterCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, My_Height(114) + (SCREEN_H - My_Height(284)), SCREEN_W, My_Height(110)) collectionViewLayout:layout];
        
        [_filterCollection setBackgroundColor:[UIColor blackColor]];
        
        [_filterCollection setTag:102];
        
        [_filterCollection setShowsHorizontalScrollIndicator:NO];
        
        [_filterCollection registerClass:[FilterCollectionViewCell class] forCellWithReuseIdentifier:@"filterCell"];
        
        [_filterCollection setDataSource:self];
        
        [_filterCollection setDelegate:self];
    }
    
    return _filterCollection;
}

- (UIButton *) scaleBtn {

    if (!_scaleBtn) {
        
        _scaleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_scaleBtn setFrame:CGRectMake(SCREEN_W - My_Width(40), My_Height(89) + (SCREEN_H - My_Height(284)), My_Height(20), My_Height(20))];
        
        [_scaleBtn setImage:[UIImage imageNamed:@"set_icon"] forState:UIControlStateNormal];
        
        [_scaleBtn addTarget:self action:@selector(action_scaleBtnClickEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _scaleBtn;
}

- (CIContext *) context {

    if (!_context) {
        
        _context = [CIContext contextWithOptions:nil];
    }
    
    return _context;
}

- (UICollectionView *) optionCollection {

    if (!_optionCollection) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
        [layout setMinimumInteritemSpacing:0.0];
        
        [layout setMinimumLineSpacing:0.0];
        
        _optionCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, (SCREEN_H - My_Height(60)), SCREEN_W, My_Height(60)) collectionViewLayout:layout];
        
        [_optionCollection setTag:101];
        
        [_optionCollection setBackgroundColor:[UIColor blackColor]];
        
        [_optionCollection setShowsHorizontalScrollIndicator:NO];
        
        [_optionCollection registerClass:[POptionCollectionViewCell class] forCellWithReuseIdentifier:@"optionCell"];
        
        [_optionCollection setDataSource:self];
        
        [_optionCollection setDelegate:self];
    }
    
    return _optionCollection;
}

+ (ImageProcessViewController *)shardImagePrecessViewController {

    static ImageProcessViewController *imageVC = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        imageVC = [[ImageProcessViewController alloc] init];
    });
    
    return imageVC;
}

- (EffectView *)effectView {

    if (!_effectView) {
        
        _effectView = [[EffectView alloc] initWithFrame:CGRectMake(0, My_Height(114) + (SCREEN_H - My_Height(284)), SCREEN_W, My_Height(110)) oldImage:_oldImage imageView:self.contextImageView];
        
        [_effectView setAlpha:0];
    }
    
    return _effectView;
}

- (UIButton *) resetBtn {

    if (!_resetBtn) {
        
        _resetBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_resetBtn setFrame:CGRectMake(My_Width(20), My_Height(89) + (SCREEN_H - My_Height(284)), My_Height(40), My_Height(20))];
        
        [_resetBtn.titleLabel setTextColor:[UIColor whiteColor]];
        
        [_resetBtn setTitle:@"撤销" forState:UIControlStateNormal];
        
        [_resetBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        
        [_resetBtn addTarget:self action:@selector(action_resetBtnClickEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _resetBtn;
}

@end
